package com.rongma.waterdrop.activity;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Process;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.rongma.waterdrop.R;
import com.rongma.waterdrop.exception.UserException;
import com.rongma.waterdrop.exception.WrongScoreException;
import com.rongma.waterdrop.fragment.SettingFragment;
import com.rongma.waterdrop.fragment.ToolsFragment;
import com.rongma.waterdrop.fragment.TrainingFragment;
import com.rongma.waterdrop.fragment.WaterDropFragment;
import com.rongma.waterdrop.global.BaseFragmentActivity;
import com.rongma.waterdrop.manager.bmobmanager.UserManager;
import com.rongma.waterdrop.model.User;
import com.rongma.waterdrop.receiver.AlarmReceiver;
import com.rongma.waterdrop.utils.ActivityCollector;
import com.rongma.waterdrop.utils.Arith;
import com.rongma.waterdrop.utils.LogUtils;
import com.rongma.waterdrop.utils.ScoreUtil;

import java.util.ArrayList;
import java.util.Calendar;


public class MainActivity extends BaseFragmentActivity {

    private RadioGroup rgBottom;
    private RadioButton rbWaterDrop;
    private RadioButton rbTools;
    private RadioButton rbTraining;
    private RadioButton rbSetting;
    private DrawerLayout drawerLayout;
    private WaterDropFragment waterDropFragment;
    private ToolsFragment toolsFragment;
    private TrainingFragment trainingFragment;
    private SettingFragment settingFragment;
    private ListView mLvMenuList;
    private ImageView mIvProtrait;
    private TextView mTvUserName;
    private TextView mTvScore;
    private TextView mTvSign;
    private ArrayAdapter<String> adapter;

    private long editTime; //用于记录按退出键的时间间隔


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected void initViriables() {

    }

    @Override
    protected void bindView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        //绑定控件
        rgBottom = (RadioGroup) findViewById(R.id.rg_nav_bottom);
        rbWaterDrop = (RadioButton) findViewById(R.id.rb_bottom_waterdrop);
        rbTools = (RadioButton) findViewById(R.id.rb_bottom_tools);
        rbTraining = (RadioButton) findViewById(R.id.rb_bottom_training);
        rbSetting = (RadioButton) findViewById(R.id.rb_bottom_setting);
        drawerLayout = (DrawerLayout)findViewById(R.id.waterdrop_main_drawerlayout);
        mLvMenuList = (ListView)findViewById(R.id.lv_menu_content);
        mIvProtrait = (ImageView)findViewById(R.id.iv_protrait);
        mTvUserName = (TextView)findViewById(R.id.tv_username);
        mTvScore = (TextView)findViewById(R.id.tv_score);
        mTvSign = (TextView)findViewById(R.id.tv_sign);
        //设置Menu的条目
        AddMenuItem();
        //绑定事件
        rgBottom.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                clearTextColor();
                select(checkedId);
            }
        });
        select(R.id.rb_bottom_waterdrop);
        //获取User数据
        try {
            User user = UserManager.getManager(MainActivity.this).queryUserByName("戎码");
            mTvUserName.setText("戎码");
            mTvScore.setText(ScoreUtil.getRankByScoreAndTime(user.getScore(),user.getCodeTime()));
            mTvSign.setText(user.getSignature());
            Glide.with(MainActivity.this)
                    .load(user.getImageFileUrl())
                    .centerCrop()
                    .into(mIvProtrait);
        } catch (WrongScoreException e) {
            LogUtils.show(e.getMessage());
            e.printStackTrace();
        } catch (UserException e) {
            LogUtils.show(e.getMessage());
            e.printStackTrace();
        }
    }

    //设置侧边栏的ListView条目
    private void AddMenuItem() {
        ArrayList<String> items = new ArrayList<String>();
        items.add("排行榜");
        items.add("任务管理");
        items.add("语音日记");
        items.add("知乎日报");
        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items);
        mLvMenuList.setAdapter(adapter);
        mLvMenuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                switch (position)
                {
                    case 0:
                        toOtherActivity(RankActivity.class);
                        break;
                    case 1:
                        toOtherActivity(TaskActivity.class);
                        break;
                    case 2:
                        toOtherActivity(DiaryActivity.class);
                        break;
                    case 3:
                        toOtherActivity(ZhihuDailyActivity.class);
                        break;
                }
            }
        });
    }

    private void clearTextColor() {
        rbWaterDrop.setTextColor(getResources().getColor(R.color.colorBottomText));
        rbTools.setTextColor(getResources().getColor(R.color.colorBottomText));
        rbTraining.setTextColor(getResources().getColor(R.color.colorBottomText));
        rbSetting.setTextColor(getResources().getColor(R.color.colorBottomText));
    }

    //选中RadioButton选项,设置文本颜色\加载布局
    private void select(int id) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        hideFragment(transaction); //判断Fragment是否为空,如果不为空,就调用hide()
        switch(id)
        {
            case R.id.rb_bottom_waterdrop:
                rbWaterDrop.setTextColor(getResources().getColor(R.color.colorPrimary));
                if(waterDropFragment == null)
                {
                    waterDropFragment = new WaterDropFragment();
                    transaction.add(R.id.content_layout,waterDropFragment);
                }
                else
                {
                    transaction.show(waterDropFragment);
                }
                break;
            case R.id.rb_bottom_tools:
                rbTools.setTextColor(getResources().getColor(R.color.colorPrimary));
                if(toolsFragment == null)
                {
                    toolsFragment = new ToolsFragment();
                    transaction.add(R.id.content_layout,toolsFragment);
                }
                else
                {
                    transaction.show(toolsFragment);
                }
                break;
            case R.id.rb_bottom_training:
                rbTraining.setTextColor(getResources().getColor(R.color.colorPrimary));
                if(trainingFragment == null)
                {
                    trainingFragment = new TrainingFragment();
                    transaction.add(R.id.content_layout,trainingFragment);
                }
                else
                {
                    transaction.show(trainingFragment);
                }
                break;
            case R.id.rb_bottom_setting:
                rbSetting.setTextColor(getResources().getColor(R.color.colorPrimary));
                if(settingFragment == null)
                {
                    settingFragment = new SettingFragment();
                    transaction.add(R.id.content_layout,settingFragment);
                }
                else
                {
                    transaction.show(settingFragment);
                }
                break;
        }
        transaction.commit();
    }

    //清除所有的Fragment
    private void hideFragment(FragmentTransaction transaction) {
        if(waterDropFragment != null)
        {
            transaction.hide(waterDropFragment);
        }
        if(toolsFragment != null)
        {
            transaction.hide(toolsFragment);
        }
        if(trainingFragment != null)
        {
            transaction.hide(trainingFragment);
        }
        if(settingFragment != null)
        {
            transaction.hide(settingFragment);
        }
    }


    @Override
    protected void getData() {
        AlarmManager  alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        Intent intent = new Intent(AlarmReceiver.ALARM_RECEIVER_ACTION);
        PendingIntent pendingIntent=PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode)
        {
            case KeyEvent.KEYCODE_BACK:
                if (Arith.sub(System.currentTimeMillis(), editTime) > 1500) {
                    showToast("再按一次退出程序");
                    editTime = System.currentTimeMillis();
                } else {
                    ActivityCollector.finishAll();
                    Process.killProcess(Process.myPid());
                    System.exit(0);
                }
                return true;
            case KeyEvent.KEYCODE_MENU:
                if(drawerLayout.isDrawerOpen(Gravity.LEFT))
                {
                    drawerLayout.closeDrawer(Gravity.LEFT);
                }
                else
                {
                    drawerLayout.openDrawer(Gravity.LEFT);
                }
                return true;
        }
        return false;
    }
}
